<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/view/common/taglibs.jsp"%>

<!DOCTYPE>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />

    <title>新增角色</title>

    <%@ include file="/WEB-INF/view/common/common.jsp"%>
    <script src="${_cdnStaticResourcesPath}/resources/static/js/jquery-fixed.js" type="text/javascript" ></script>
    <script src="${_cdnStaticResourcesPath}/resources/static/js/plugins/validform/Validform.js" type="text/javascript"></script>
</head>
<body>
<div class="clearfix">
    <div id="scrollsidebar" class="left_Treeview" style="margin-right: 10px;">
        <div class="show_btn" id="rightArrow"><span></span></div>
        <div class="widget-box side_content" style="margin-top: 0px;">
            <div class="side_title"><a title="隐藏" class="close_btn"><span></span></a></div>
            <div class="side_list">
                <div class="widget-header header-color-green2">
                    <span style="font-size: 13px;">指定角色拥有的权限</span>
                </div>
                <div>
                    <div class="widget-main padding-8">
                        <div  id="permissionTree" class="ztree"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div id="category" style="border: 1px solid #dddddd;height: 100%;">
        <div class="type_style" style="height: 100%;">
            <div class="type_title" style="font-size: 14px;">角色详细信息</div>
            <div class="type_content" style="margin-top: 0px;width: 100%;">
                <div class="margin" id="page_style">
                    <div class="add_style" style="float:left;width: 100%;">
                        <form action="${ctx}/role/addRole" method="post" id="form-role-add">
                            <input type="hidden" des="存放选中的权限id集合" id="permissionIds" name="permissionIds" value=""/>
                            <ul>
                                <li class="clearfix" style="margin-top: 0px;">
                                    <div class="alert alert-info" style="text-align: left;margin-top: 0px;margin-bottom: 10px;">
                                        <p><i class="fa fa-hand-o-right"></i>&nbsp;为角色指定权限的时候，勾选的节点背景颜色为&nbsp;<i class="fa fa-stop" style="color: #94C76D;"></i>&nbsp;，易于查看</p>
                                    </div>
                                </li>
                                <li class="clearfix">
                                    <label class="label_name col-xs-2 col-lg-2"><i class="c-red">*</i>所属应用：</label>
                                    <div class="formControls col-xs-6">
                                        <span class="select-box" style="width:150px;">
                                            <select class="select col-xs-12" name="appId" id="appId" size="1" style="height: 30px;line-height: 30px;">
                                                <c:forEach items="${apps}" var="app">
                                                    <option value="${app.id}">${app.name}</option>
                                                </c:forEach>
                                            </select>
                                        </span>
                                    </div>
                                </li>
                                <li class="clearfix">
                                    <label class="label_name col-xs-2 col-lg-2"><i class="c-red">*</i>角色名称：</label>
                                    <div class="formControls col-xs-6">
                                        <input type="text" placeholder="请输入角色名称" name="name" id="name" autocomplete="off" value="" class="input-text col-xs-12" datatype="*" nullmsg="角色名称不能为空">
                                    </div>
                                    <div class="col-4"> <span class="Validform_checktip"></span></div>
                                </li>
                                <li class="clearfix">
                                    <label class="label_name col-xs-2 col-lg-2"><i class="c-red">*</i>角色描述：</label>
                                    <div class="formControls col-xs-6">
                                        <input type="text" placeholder="请输入角色描述" name="description" id="description" autocomplete="off" value="" class="input-text col-xs-12" datatype="*" nullmsg="角色描述不能为空">
                                    </div>
                                    <div class="col-4"> <span class="Validform_checktip"></span></div>
                                </li>
                                <li class="clearfix">
                                    <label class="label_name col-xs-2 col-lg-2"><i class="c-red">*</i>状态：</label>
                                    <div class="formControls col-xs-6">
                                        <span class="select-box" style="width:150px;">
                                            <select class="select" name="status" size="1">
                                                <c:forEach items="${status}" var="s">
                                                    <option value="${s}">${s.description}</option>
                                                </c:forEach>
                                            </select>
                                        </span>
                                    </div>
                                </li>
                                <li class="clearfix" style="display: none;">
                                    <div class="col-xs-2 col-lg-2">&nbsp;</div>
                                    <div class="col-xs-9">
                                        <button class="btn btn-primary" type="button" data-loading-text="提交中..." id="btn_submit"><i class="fa fa-save"></i>&nbsp;提交信息</button>
                                        <button onclick="javascript:history.back(-1);" class="btn btn-warning" type="button"><i class="fa fa-reply"></i>&nbsp;返回上一步</button>
                                    </div>
                                </li>
                            </ul>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<input type="hidden" des="获取对应应用下的权限列表URL" name="getPermissionTreeUrl"  id="getPermissionTreeUrl" value="<c:url value="/permission/getPermissionTree"/>"/>
<input type="hidden" name="permissions" value='' des="权限列表json字符串，这里value必须是单引号，避免与permissions值中的双引号冲突，出现问题"/>
</body>
</html>


<script>

    $(document).ready(function() {
        //滚动条美化
        $(".type_style").niceScroll({
            cursorcolor:"#888888",
            cursoropacitymax:1,
            touchbehavior:false,
            cursorwidth:"5px",
            cursorborder:"0",
            cursorborderradius:"5px"
        });
        $("html").css("overflow","auto");
        //当前页面左侧菜单收缩功能
        $("#scrollsidebar").fix({
            float : 'left',
            //minStatue : true,
            skin : 'green',
            spacingw:30,//设置隐藏时的距离
            durationTime :false
        });


        getPermissionTreeData();//获取对应的应用的权限数据

        //应用下拉框改变事件，获取对应的应用的权限数据
        $("#appId").change(function () {
            $("#permissionIds").val("");//先清空隐藏域的值
            getPermissionTreeData();
        });
    });

    //表单验证提交
    var btn_submit = "#btn_submit";//提交按钮id
    $("#form-role-add").Validform({
        ajaxPost:true,
        tiptype:2,
        showAllError:true,
        postonce:true, //可选项 表单是否只能提交一次，true开启，不填则默认关闭;
        btnSubmit:btn_submit,
        callback:function(data){
            if(data.code == 200){
                $.message("保存成功");
            }else{
                $.message({
                    message:data.msg,
                    type:'error'
                });
                return false;
            }
            window.parent.searchData();//重新加载数据表
        }
    });

    /**
     * 获取应用的权限tree数据
     */
    function getPermissionTreeData(){
        $.ajax({
            url : $("#getPermissionTreeUrl").val(),
            async:true,
            data:{
                "appId" : $("#appId option:selected").val(),//默认获取所属应用下拉框的第一个应用权限数据
                "showTopParent" : true, //是否显示最顶级的节点【无上级权限】
                "open" : false
            },
            dataType:'json',
            success:function(data,textStatus,jqXHR){
                $("input[name='permissions']").val(data);
                loadTree();
            },
            error:function(xhr,textStatus){}
        });
    }

    /**
     * 加载权限tree
     */
    function loadTree(){
        var setting = {
            check : {
                enable : true
            },
            data : {
                simpleData : {
                    enable : true
                }
            },
            callback : {
                onCheck : function(event, treeId, treeNode){//节点被点击后，设置选择的节点id
                    permissionNodeSelect();//选中了节点，赋予最新权限id列表给隐藏域
                    reloadNodeCheckChangeBackColor(treeNode);//设置check被改变的节点背景色
                },
                onClick : function (event, treeId, treeNode) {
                    if(treeNode.isParent){
                        var treeObj = $.fn.zTree.getZTreeObj("permissionTree");
                        treeObj.expandNode(treeNode);
                    }
                }
            }
        };
        var roles = $("input[name='permissions']").val();
        $.fn.zTree.init($("#permissionTree"), setting, eval("(" + roles + ")"));

        var zTree = $.fn.zTree.getZTreeObj("permissionTree"), type = {"Y" : "ps","N" : "s"};
        zTree.setting.check.chkboxType = type;

        //tree加载显示完毕后，移除[无上级节点]这个节点
        var treeObj = $.fn.zTree.getZTreeObj("permissionTree");
        var node = treeObj.getNodeByParam("id", -1, null);
        if(node != null){
            treeObj.removeNode(node);
        }
    }


    /**
     * 设置check被改变的节点背景色
     */
    function reloadNodeCheckChangeBackColor(treeNode) {
        var treeObj = $.fn.zTree.getZTreeObj("permissionTree");
        if(treeNode.checked){
            treeObj.expandNode(treeNode,true,true);//展开当前节点
        }else{
            if(treeNode.isParent){
                treeObj.expandNode(treeNode,false,true);//收缩当前节点以及子节点
            }
        }
        changeChildrenNodesBackColor(treeNode);
        /*var treeObj = $.fn.zTree.getZTreeObj("permissionTree");
        var nodes = treeObj.getChangeCheckedNodes();//获取输入框勾选状态被改变的节点集合（与原始数据 checkedOld 对比）
        if(nodes != null && nodes.length > 0){
            for(var i = 0,len=nodes.length; i < len; i++){
                if(nodes[i].checked){
                    $("#" + nodes[i].tId + "_a").css("backgroundColor","#AAE5B7");//角色之前已经有的权限
                }else{
                    if(treeNode.isParent){//如果是父节点，则取消所有子节点背景色
                        changeChildrenNodesBackColor(treeNode);
                    }
                    //$("#" + nodes[i].tId + "_a").css("backgroundColor","#fff");//设置选中的节点的背景颜色
                }
            }
        }*/
    }

    /**
     * 递归方法。设置父节点的背景色
     */
    function changeParentNodesBackColor(treeNode){
        var parentNode = treeNode.getParentNode();
        if(parentNode == null){
            return;
        }
        if(treeNode.checked){
            $("#" + parentNode.tId + "_a").css("backgroundColor","#AAE5B7");//设置选中的节点的背景颜色
            changeParentNodesBackColor(parentNode);
        }
    }

    /**
     * 递归方法，清空所有子节点的背景色
     */
    function changeChildrenNodesBackColor(treeNode) {
        if (treeNode.isParent) {

            if(treeNode.checked){
                changeParentNodesBackColor(treeNode);//设置所有父节点的背景色

                $("#" + treeNode.tId + "_a").css("backgroundColor","#AAE5B7");
                var childrenNodes = treeNode.children;
                if (childrenNodes) {
                    for (var i = 0,len = childrenNodes.length; i < len; i++) {
                        $("#" + childrenNodes[i].tId + "_a").css("backgroundColor","#AAE5B7");
                        changeChildrenNodesBackColor(childrenNodes[i]);
                    }
                }
            }else{
                $("#" + treeNode.tId + "_a").css("backgroundColor","#fff");
                var childrenNodes = treeNode.children;
                if (childrenNodes) {
                    for (var i = 0,len = childrenNodes.length; i < len; i++) {
                        $("#" + childrenNodes[i].tId + "_a").css("backgroundColor","#fff");
                        changeChildrenNodesBackColor(childrenNodes[i]);
                    }
                }
            }
        }else{
            if(treeNode.checked){
                changeParentNodesBackColor(treeNode);//设置所有父节点的背景色
                $("#" + treeNode.tId + "_a").css("backgroundColor","#AAE5B7");
            }else{
                $("#" + treeNode.tId + "_a").css("backgroundColor","#fff");
            }
        }
    }
    /**
     * 选中权限tree节点的事件，赋予hidden的值为最新选中的权限id列表
     */
    function permissionNodeSelect() {
        var numberval = 0;
        var treeRole = $.fn.zTree.getZTreeObj("permissionTree"),
            roles = treeRole.getCheckedNodes(true),
            pmss = "";
        if (roles.length > 0) {
            for (var i = 0; i < roles.length; i++) {
                pmss += roles[i].id + ",";
            }
            if (pmss.length > 0) {
                pmss = pmss.substring(0, pmss.length - 1);
            }
            $("#permissionIds").val(pmss);
        } else {
            $("#permissionIds").val("");//没有选中权限节点的，则清空隐藏域的值
            numberval++;
        }
        if (numberval > 0) {
            return false;
        }
        return true;
    }
</script>
